/****************************
 * 名称：微服务
 * 功能：Easy-D服务层开发框架
 ****************************/

/**
 * 导入需要的第三方模块
 **/  
var express 	 = require('express');
var http 		 = require('http');
var bodyParser   = require('body-parser');
var fs 			 = require('fs');

/**
 * 获取配置信息
 **/
global.config    = require('./config').configInfo;

/**
 * 创建公共全局变量
 **/
global.log4js	   		  = require('log4js');
global.async     		  = require('async');
global.RES  	   		  = require('./framework/lib/response');
global.R  	  			  = require('./framework/lib/request');
global.MESSAGE   		  = require('./framework/message/systemMessage');
global.common    		  = require('./framework/lib/commonFunc');
global.V   				  = require('./framework/lib/verification');
global.regexpRule         = require("./framework/lib/regexpConfig").regexpRule;
global.request    		  = require('request');
global.db                 = require('./framework/lib/db');
global.F			      = require('./framework/lib/processControl');

//判断API文件是否存在，存在
var exists = fs.existsSync(__dirname + "/" + config.server.businessPath);
if(exists){
	global.CORE_APIConfig	= require('./'+config.server.businessPath+'/api/core_api');
	global.APIConfig 		= require('./'+config.server.businessPath+'/api/api');
}else{
	console.log('提示：您还没有创建业务目录,所有请求接口都将转发至核心层进行处理');
	global.APIConfig = { API : {} };
}

var systemCoreApi = require('./framework/api/systemCoreApi');
for(var k in systemCoreApi.systemCoreAPI) {
	global.CORE_APIConfig.coreAPI[k] = systemCoreApi.systemCoreAPI[k]
}

//合并系统内置接口配置
var systemApi = require('./framework/api/systemApi');
for(var k in systemApi.systemApi) {
	global.APIConfig.API[k] = systemApi.systemApi[k]
}

/**
 * 配置日志信息
 **/
log4js.configure({
	appenders : config.log4.appenders
});


/**
 * 创建局部工具变量
 **/
var urlFilter = require("./framework/lib/urlFilter");
var urlParse  = require("./framework/lib/urlParse");
var urlPermission = require('./framework/lib/permissionsVerification');

/**
 * 生成http服务对象
 **/
global.app = express();

/**
 * 加载中间件部分
 **/
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

/**
 * URL检测
 **/
app.all("*",function(req,res,next){
	  urlFilter['Url'](req,res,next);
});


/**
 * ec_web_api接口路由部分
 * urlParse.APIisExist  		  : 查看该接口是否存在
 * urlParse.APIisMethod  		  : 查看该接口请求方式是否正确
 * urlParse.APIgetParams 		  : 解析接口参数信息
 * urlParse.APIParamsVerification : 参数格式验证
 **/
app.all(["/:firstMenuLevel/:secondMenuLevel/*","/:firstMenuLevel/:secondMenuLevel"],
		urlParse.APIAppTokenVerification,
		urlPermission.Vpermissions,
		urlParse.APIisExist,
		urlParse.APIisMethod,
		urlParse.APIgetParams,
		urlParse.APIParamsVerification,
		function(req,res) {

			var route = null;

			//根据接口类型进行不一样的路由处理
			if(req.routeInfo.apiType == 'SYSTEM'){

				//获取请求路由
				route = require("./framework/routes/" + req.routeInfo.apiFullName);

			}else {

				//获取请求路由
				route = require("./" + config.server.businessPath + "/routes/" + req.routeInfo.apiFullName);

			}


			//执行接口处理方法
			route[req.routeInfo.secondMenuLevelName](req,res);
		
});


app.all('*', function(req, res){
	res.end('该接口不存在，请重新确认');
});

/**
 * 启动服务器
 **/
if(config.base.isClusterStart){  //判断是否以集群方式启动

	//导入群集处理模块
	var cluster 	 = require('cluster');
	var os 			 = require('os');

	//获取 CPU 的数量
	var cpuCount = os.cpus().length;

	//声明工作进程池
	var workers = {};


	if(cluster.isMaster) {

		//当一个工作进程结束时，重启工作进程
		cluster.on('death', function (worker) {
			delete workers[worker.pid];
			worker = cluster.fork();
			workers[worker.pid] = worker;
		});

		// 声明工作进程
		var worker;

		// 开启与 CPU 数量相同的工作进程
		for (var i = 0; i < cpuCount; i++) {
			worker = cluster.fork();
			workers[worker.pid] = worker;
		}

	}else{

		//启动服务器
		http.createServer(app).listen(config.server.port, function(){
			console.log('服务器正常启动...端口号:' + config.server.port);
		});

	}

	// 当主进程被终止时，关闭所有工作进程
	process.on('SIGTERM', function () {
		for (var pid in workers) {
			if (!workers.hasOwnProperty(pid)) {
				continue;
			}
			process.kill(pid);
		}
		process.exit(0);
	});

}else{

	//启动服务器
	http.createServer(app).listen(config.server.port, function(){
		console.log('服务器正常启动...端口号:' + config.server.port);
	});

}